package com.xiaodou.mjf.web.xface.core.controller.ibp.v1.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.xiaodou.mjf.application.basic.utils.SequenceGenerator;
import com.xiaodou.mjf.application.core.service.InvokeLogService;
import com.xiaodou.mjf.application.core.service.OrderService;
import com.xiaodou.mjf.entity.core.InvokeLog;
import com.xiaodou.mjf.entity.core.Order;
import com.xiaodou.mjf.entity.core.Sequence;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.CodeGenerator;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.infrastructure.payeco.Payeco;
import com.xiaodou.mjf.infrastructure.payeco.client.TransactionH5Client;
import com.xiaodou.mjf.infrastructure.payeco.tools.http.HttpClient;
import com.xiaodou.mjf.web.xface.common.API;
import com.xiaodou.mjf.web.xface.common.ResultCode;
import com.xiaodou.mjf.web.xface.core.controller.ibp.v1.threads.AsyncNotifyThread;
import com.xiaodou.mjf.web.xface.core.controller.ibp.v1.utils.Constants;
import com.xiaodou.mjf.web.xface.core.controller.ibp.v1.utils.MD5;
import com.xiaodou.mjf.web.xface.core.controller.ibp.v1.utils.client.TransactionClient;
import com.xiaodou.mjf.web.xface.core.controller.ibp.v1.utils.tools.Tools;
import com.xiaodou.mjf.web.xface.core.controller.ibp.v1.utils.tools.Xml;
import com.xiaodou.mjf.web.xface.core.domain.InvokeLogVO;
import com.xiaodou.mjf.web.xface.core.domain.OrderVO;
import com.xiaodou.mjf.web.xface.core.threads.OpenningAccountThread;
import com.xiaodou.mjf.web.xface.core.utils.Decrypt;
import com.xiaodou.mjf.web.xface.core.utils.TradeCode;
import org.dozer.DozerBeanMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

/**
 * Created by Rocky on 15/4/2.
 */
@Controller("com.xiaodou.mjf.web.xface.core.controller.ibp.v1.controller.PaymentController")
@RequestMapping("v1/ibp/payment")
public class PaymentController extends ApiController{

    @Resource
    OrderService orderService;
    @Resource
    InvokeLogService invokeLogService;

    @RequestMapping("h5.html")
    public String h5(HttpServletRequest request,Model model,HttpServletResponse response){

    	String code = request.getParameter("code");
        String message = request.getParameter("message");
        if(StringUtils.isBlank(code)) {
            code = "0000";
        }
        model.addAttribute("code",code);
        model.addAttribute("message",message);
        model.addAttribute("returnUrl",API.getReturnUrl());

        if(!code.equals("0000")){
            return "pay/h5";
        }


        String param = request.getParameter("param");
        param = Decrypt.doDecrypt(param);



        if(StringUtils.isBlank(param)){
            model.addAttribute("code", "W101");
            model.addAttribute("message","无效的请求参数");
            return "pay/h5";
        }

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> map = null;

        try {

            map = objectMapper.readValue(param, Map.class);

        }catch (Exception e){
            model.addAttribute("code", "W101");
            model.addAttribute("message","无效的请求参数");
            return "pay/h5";
        }

        if(map == null || map.keySet().size() == 0){
            model.addAttribute("code", "W101");
            model.addAttribute("message","无效的请求参数");
            return "pay/h5";
        }


        String extOrderId = map.get("order_id");

        Order order = orderService.get(extOrderId, Order.HAS_PAID);
        if(order != null){
            model.addAttribute("code", "W101");
            model.addAttribute("message","该订单已支付！");

            return "pay/h5";
        }

        model.addAttribute("params",map);

        return "ibp/h5";
    }

    @RequestMapping("process.html")
    public String process_(HttpServletRequest request,Model model,HttpServletResponse response){

        Map<String,String> params = Maps.newHashMap();

        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()){
            String paramName = paramNames.nextElement();
            params.put(paramName,request.getParameter(paramName));
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = StringUtils.EMPTY;
        try {
            jsonStr = objectMapper.writeValueAsString(params);
        }catch (Exception e){
            logger.debug("参数转换失败",e.getMessage());
            model.addAttribute("code", "W101");
            model.addAttribute("message","无效的请求参数");
            return "redirect:h5.html?code="+ResultCode.MISSING_PARAMS;
        }

        InvokeLogVO logVO = null;
        OrderVO orderVO = null;

        try {

            logVO = objectMapper.readValue(jsonStr, InvokeLogVO.class);
            orderVO = objectMapper.readValue(jsonStr, OrderVO.class);
        }catch (Exception e){
            logger.debug("参数转换失败",e.getMessage());
            model.addAttribute("code", "W101");
            model.addAttribute("message","无效的请求参数");
            return "redirect:h5.html?code="+ResultCode.MISSING_PARAMS;
        }

        logVO.setMessage(jsonStr);

        if(logVO.getTradeCode().equals("001")) {

            try {

                Order order = orderService.get(orderVO.getOrderId(), Order.HAS_PAID);
                if (order != null) {
                    logger.debug("订单已支付");
                    model.addAttribute("code", ResultCode.ORDER_HAS_BEAN_PAID);
                    model.addAttribute("message","该订单已支付");
                    return "redirect:h5.html?code="+ResultCode.ORDER_HAS_BEAN_PAID+"&message="+URLEncoder.encode("该订单已支付","utf-8");
                }

                DozerBeanMapper mapper = new DozerBeanMapper();

                InvokeLog log = mapper.map(logVO, InvokeLog.class);
                order = mapper.map(orderVO, Order.class);

                order.setType(Order.TYPE_PAYMENT);
                order.setPaymentStatus(Order.WAIT_PAYMENT);
                order.setTxnDate(DateUtils.getCurrentTime());
                order.setExtOrderId(orderVO.getOrderId());
                if(StringUtils.isNotBlank(order.getMerchantName()))
                    order.setMerchantName(URLDecoder.decode(order.getMerchantName(), "UTF-8"));
                if(StringUtils.isNotBlank(order.getRealName()))
                    order.setRealName(URLDecoder.decode(order.getRealName(), "UTF-8"));
                order.setDescription(URLDecoder.decode(order.getDescription(), "UTF-8"));

                order.setSerialNumber(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));


                orderService.save(order);

                log.setMerchantName(order.getMerchantName());
                log.setOrderId(order.getId());
                log.setExtOrderId(order.getExtOrderId());
                invokeLogService.save(log);

                String merchantId = Payeco.IF.merchant_id;
                String notifyUrl = API.getIbpNotifyUrl();  //需要做URLEncode
                String returnUrl = API.getIbpReturnUrl();  //需要做URLEncode
                String tradeTime = Tools.getSysTime();
                String expTime = ""; //采用系统默认的订单有效时间
                String notifyFlag = "0";
                String priKey = Payeco.IF.private_key;
                String pubKey = Payeco.IF.collection_public_key;
                String payecoUrl = Payeco.IF.collection_url;
                String extData = StringUtils.EMPTY;
                //String miscData = "13661634728|||商户测试|440106196911211822|6225887803700003|||";
                String miscData = String.format("%s|||%s|%s|%s||%s||2|", order.getMobile(),order.getRealName(),order.getCertNo(), orderVO.getCardNumber(), SequenceGenerator.generateOrder(SequenceGenerator.TYPE_DEPOSIT));

                Xml xml = new Xml();


                String ret = TransactionClient.MerchantOrderH5(merchantId, order.getId(), String.valueOf(order.getAmount()), order.getDescription(),
                        tradeTime, expTime, notifyUrl, returnUrl, extData, miscData, notifyFlag, request.getRemoteAddr(),
                        priKey, pubKey, payecoUrl,xml);
                if (!ret.equals("0000")) {
                    String url = API.getHost() + "/v1/ibp/payment/h5.html?";
                    url += "reload=true&code="+ret+"&message="+ URLEncoder.encode(xml.getRetMsg(), "utf-8");

                    response.sendRedirect(url);
                    return null;
                }

                String redirectUrl = TransactionClient.getPayInitRedirectUrl(Payeco.IF.collection_url,xml);
                response.sendRedirect(redirectUrl);

            }catch (Exception e){
                logger.error(e.getMessage());
                model.addAttribute("code","E1001");
                model.addAttribute("message","下单失败");
                return "pay/h5";
            }
        }else if(logVO.getTradeCode().equals(TradeCode.DEPOSIT)){

            try {

                DozerBeanMapper mapper = new DozerBeanMapper();

                InvokeLog log = mapper.map(logVO, InvokeLog.class);
                Order order = mapper.map(orderVO, Order.class);

                String orderId = CodeGenerator.UUID();

                order.setId(orderId);
                order.setType(Order.TYPE_DEPOSIT);
                order.setPaymentStatus(Order.WAIT_PAYMENT);
                order.setTxnDate(DateUtils.getCurrentTime());
                order.setExtOrderId(orderId);
                if (StringUtils.isNotBlank(order.getRealName()))
                    order.setRealName(URLDecoder.decode(order.getRealName(), "UTF-8"));
                order.setSerialNumber(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));

                order.setDescription(URLDecoder.decode(order.getDescription(), "UTF-8"));

                orderService.save(order);

                log.setMerchantName(order.getMerchantName());
                log.setOrderId(order.getId());
                invokeLogService.save(log);

                String merchantId = Payeco.IF.merchant_id;
                String notifyUrl = API.getIbpNotifyUrl();  //需要做URLEncode
                String returnUrl = API.getIbpReturnUrl();  //需要做URLEncode
                String tradeTime = Tools.getSysTime();
                String expTime = ""; //采用系统默认的订单有效时间
                String notifyFlag = "0";
                String priKey = Payeco.IF.private_key;
                String pubKey = Payeco.IF.collection_public_key;
                String payecoUrl = Payeco.IF.collection_url;
                String extData = StringUtils.EMPTY;
                //String miscData = "13661634728|||商户测试|440106196911211822|6225887803700003|||";
                String miscData = String.format("%s|||%s|%s|%s||%s||2|", order.getMobile(),order.getRealName(),order.getCertNo(), orderVO.getCardNumber(), SequenceGenerator.generateOrder(SequenceGenerator.TYPE_DEPOSIT));

                Xml xml = new Xml();


                String ret = TransactionClient.MerchantOrderH5(merchantId, order.getId(), String.valueOf(order.getAmount()), order.getDescription(),
                        tradeTime, expTime, notifyUrl, returnUrl, extData, miscData, notifyFlag, request.getRemoteAddr(),
                        priKey, pubKey, payecoUrl, xml);
                if (!ret.equals("0000")) {
                    //return failure(ResultCode.PAYECO_ERROR);
                    //return failure(xml.getRetCode(), xml.getRetMsg());
                    //                    String url = log.getReturnUrl();
                    //                    url += "?code=W102&message="+URLEncoder.encode("支付金额超限","UTF-8");
                    String url = API.getHost() + "/v1/ibp/payment/h5.html?";
                    url += "reload=true&code=" + ret + "&message=" + URLEncoder.encode(xml.getRetMsg(), "utf-8");
                    response.sendRedirect(url);
                }

                String redirectUrl = TransactionClient.getPayInitRedirectUrl(Payeco.IF.collection_url,xml);

                response.sendRedirect(redirectUrl);
            }catch (Exception e){
                logger.error("充值失败:{}",e.getMessage());
                model.addAttribute("code","E1001");
                model.addAttribute("message","充值失败");
                return "pay/h5";
            }
        }else if(logVO.getTradeCode().equals("002")){

        }else if(logVO.getTradeCode().equals("004")){
            try {

                DozerBeanMapper mapper = new DozerBeanMapper();

                InvokeLog log = mapper.map(logVO, InvokeLog.class);
                Order order = mapper.map(orderVO, Order.class);

                String orderId = CodeGenerator.UUID();

                order.setId(orderId);
                order.setType(Order.TYPE_DEPOSIT);
                order.setPaymentStatus(Order.WAIT_PAYMENT);
                order.setTxnDate(DateUtils.getCurrentTime());
                order.setExtOrderId(orderId);
                if (StringUtils.isNotBlank(order.getRealName()))
                    order.setRealName(URLDecoder.decode(order.getRealName(), "UTF-8"));
                order.setSerialNumber(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));

                order.setDescription(URLDecoder.decode(order.getDescription(), "UTF-8"));

                orderService.save(order);

                log.setMerchantName(order.getMerchantName());
                log.setOrderId(order.getId());
                invokeLogService.save(log);

                String merchantId = Payeco.IF.merchant_id;
                String notifyUrl = API.getIbpNotifyUrl();  //需要做URLEncode
                String returnUrl = API.getIbpReturnUrl();  //需要做URLEncode
                String tradeTime = Tools.getSysTime();
                String expTime = ""; //采用系统默认的订单有效时间
                String notifyFlag = "0";
                String priKey = Payeco.IF.private_key;
                String pubKey = Payeco.IF.collection_public_key;
                String payecoUrl = Payeco.IF.collection_url;
                String extData = StringUtils.EMPTY;
                //String miscData = "13661634728|||商户测试|440106196911211822|6225887803700003|||";
                String miscData = String.format("%s|||%s|%s|%s||%s||2|", order.getMobile(),order.getRealName(),order.getCertNo(), orderVO.getCardNumber(), SequenceGenerator.generateOrder(SequenceGenerator.TYPE_DEPOSIT));

                Xml xml = new Xml();


                String ret = TransactionClient.MerchantOrderH5(merchantId, order.getId(), String.valueOf(order.getAmount()), order.getDescription(),
                        tradeTime, expTime, notifyUrl, returnUrl, extData, miscData, notifyFlag, request.getRemoteAddr(),
                        priKey, pubKey, payecoUrl, xml);
                if (!ret.equals("0000")) {
                    //return failure(ResultCode.PAYECO_ERROR);
                    //return failure(xml.getRetCode(), xml.getRetMsg());
                    //                    String url = log.getReturnUrl();
                    //                    url += "?code=W102&message="+URLEncoder.encode("支付金额超限","UTF-8");
                    String url = API.getHost() + "/v1/core/payment/h5.html?";
                    url += "reload=true&code=" + ret + "&message=" + URLEncoder.encode(xml.getRetMsg(), "utf-8");
                    response.sendRedirect(url);
                }

                String redirectUrl = TransactionClient.getPayInitRedirectUrl(payecoUrl,xml);

                response.sendRedirect(redirectUrl);
            }catch (Exception e){
                logger.error("还款失败:{}",e.getMessage());
                model.addAttribute("code","E1001");
                model.addAttribute("message","还款失败");
                return "pay/h5";
            }
        }

        model.addAttribute("code","E1001");
        model.addAttribute("message","下单异常");
        return "pay/h5";
    }

    @RequestMapping("remote/notify")
    @ResponseBody
    public String notify(HttpServletRequest request) throws Exception{

        request.setCharacterEncoding("utf-8");

        Enumeration<String> paramNames = request.getParameterNames();
        String p = "";
        while (paramNames.hasMoreElements()){
            String paramName = paramNames.nextElement();
            p += paramName + "=" + request.getParameter(paramName) + "&";
        }
        System.out.println(p);

        String ORDER_NO = request.getParameter("ORDER_NO");
        String MERCHANT_NO = request.getParameter("MERCHANT_NO");
        String YL_BATCH_NO = request.getParameter("YL_BATCH_NO");
        String SN = request.getParameter("SN");
        String AMOUNT = request.getParameter("AMOUNT");
        String CURRENCY = request.getParameter("CURRENCY");
        String ACCOUNT_NO = request.getParameter("ACCOUNT_NO");
        String MOBILE_NO = request.getParameter("MOBILE_NO");
        String RESP_CODE = request.getParameter("RESP_CODE");
        String RESP_REMARK = request.getParameter("RESP_REMARK");
        RESP_REMARK = new String(RESP_REMARK.getBytes(),"UTF-8") ;
        String SETT_AMOUNT = request.getParameter("SETT_AMOUNT");
        String SETT_CURRENCY = request.getParameter("SETT_CURRENCY");
        String EXCHANGE_RATE = request.getParameter("EXCHANGE_RATE");
        String NOTIFY_TIME = request.getParameter("NOTIFY_TIME");
        String MER_ORDER_NO = request.getParameter("MER_ORDER_NO");
        String TRANS_DESC = request.getParameter("TRANS_DESC");
        TRANS_DESC = new String(TRANS_DESC.getBytes(),"utf-8") ;
        String MAC = request.getParameter("MAC");

        StringBuffer macSb = new StringBuffer(MERCHANT_NO);
        if (!"".equals(ORDER_NO) && ORDER_NO != null )
            macSb.append(" " + ORDER_NO);
        if (!"".equals(YL_BATCH_NO) && YL_BATCH_NO != null)
            macSb.append(" " + YL_BATCH_NO);
        if (!"".equals(SN) && SN != null)
            macSb.append(" " + SN);
        if (!"".equals(AMOUNT) && AMOUNT != null)
            macSb.append(" " + formatAmount(Double.parseDouble(AMOUNT))); // 固定两位小数
        if (!"".equals(CURRENCY) && CURRENCY != null)
            macSb.append(" " + CURRENCY);
        if (!"".equals(ACCOUNT_NO) && ACCOUNT_NO != null)
            macSb.append(" " + ACCOUNT_NO);
        if (!"".equals(MOBILE_NO) && MOBILE_NO != null)
            macSb.append(" " + MOBILE_NO);
        if (!"".equals(RESP_CODE) && RESP_CODE != null)
            macSb.append(" " + RESP_CODE);
        if (!"".equals(SETT_AMOUNT) && SETT_AMOUNT != null)
            macSb.append(" " + formatAmount(Double.parseDouble(SETT_AMOUNT))); // 固定两位小数
        if (!"".equals(MER_ORDER_NO) && MER_ORDER_NO != null)
            macSb.append(" " + MER_ORDER_NO);

        String mer_key = Payeco.IF.payeco_no_key.split("\\|")[1];
        if (!"".equals(mer_key) && mer_key != null)
            macSb.append(" " + mer_key);
        String mac = macSb.toString().toUpperCase();
        System.out.println("MAC源码:" + mac);
        MD5 md5 = new MD5();
        mac = md5.getMD5ofStr(mac);

        if(mac.equals(MAC)){
            logger.debug("MAC校验通过");

            if(RESP_CODE.equals("0000")){

                Order order = orderService.get(MER_ORDER_NO);
                if(order != null && order.getPaymentStatus().equals(Order.WAIT_PAYMENT)){
                    order.setPaymentStatus(Order.HAS_PAID);
                    order.setProcDate(DateUtils.getCurrentTime());
                    orderService.save(order);
                }

                InvokeLog log = invokeLogService.getByOrderId(order.getId());
                new AsyncNotifyThread(log.getNotifyUrl(),order.getExtOrderId(),Double.parseDouble(AMOUNT),order.getChannelId(),log.getTradeCode(),DateUtils.formatDate(DateUtils.getCurrentTime(), "yyyyMMddHHmmss"),"0000","支付成功").start();

            }else {


                Order order = orderService.get(MER_ORDER_NO);
//                if(order != null && order.getPaymentStatus().equals(Order.WAIT_PAYMENT)){
//                    order.setPaymentStatus(Order.HAS_PAID);
//                    order.setProcDate(DateUtils.getCurrentTime());
//                    orderService.save(order);
//                }

                InvokeLog log = invokeLogService.getByOrderId(order.getId());
                new AsyncNotifyThread(log.getNotifyUrl(),order.getExtOrderId(),Double.parseDouble(AMOUNT),order.getChannelId(),log.getTradeCode(),DateUtils.formatDate(DateUtils.getCurrentTime(),"yyyyMMddHHmmss"),"E102","支付失败").start();

            }


        }else{
            System.out.println("MAC校验失败，商户需主动向易联发出查询请求");
            return "FAILURE";
        }



        return "SUCCESS";
    }

    @RequestMapping("remote/return")
    public void return_(HttpServletRequest request,HttpServletResponse response) throws IOException {
        // 结果通知参数，易联异步通知采用GET提交
        String version = request.getParameter("Version");
        String merchantId = request.getParameter("MerchantId");
        String merchOrderId = request.getParameter("MerchOrderId");
        String amount = request.getParameter("Amount");
        String extData = request.getParameter("ExtData");
        String orderId = request.getParameter("OrderId");
        String status = request.getParameter("Status");
        String payTime = request.getParameter("PayTime");
        String settleDate = request.getParameter("SettleDate");
        String sign = request.getParameter("Sign");

        String respCode = request.getParameter("respCode");

        Enumeration<String> paramNames = request.getParameterNames();
        String p = "";
        while (paramNames.hasMoreElements()){
            String paramName = paramNames.nextElement();
            p += paramName + "=" + request.getParameter(paramName) + "&";
        }
        System.out.println(p);
        logger.debug(p);


        // 需要对必要输入的参数进行检查，本处省略...

        String retCode = request.getParameter("respCode");
        String baseUrl = API.getHost() + "/v1/order/return_url";
        //String baseUrl = "pay";
        if(retCode !=null && retCode.equals("W101")) {
            String url = baseUrl + "?code=W101&message=" + URLEncoder.encode("用户退出支付", "UTF-8");
            //String url = baseUrl + "?code=W101";
            response.sendRedirect(url);
        }else if(retCode.equals("2004")){
            String url = baseUrl + "?code=W101&message="+ URLEncoder.encode("参数验证失败!","UTF-8");
            //String url = baseUrl + "?code=W101";
            response.sendRedirect(url);
        }else if(retCode.equals("2003") || retCode.equals("2002") || retCode.equals("2005")){
            //String url = baseUrl + "?code=W101";
            String url = baseUrl + "?code=W101&message="+ URLEncoder.encode("支付服务异常","UTF-8");
            response.sendRedirect(url);
        }else{

            // 订单结果逻辑处理
            String retMsgJson = "";
            try {
                //验证订单结果通知的签名
                boolean b = TransactionH5Client.bCheckNotifySign(version, merchantId, merchOrderId,
                        amount, extData, orderId, status, payTime, settleDate, sign,
                        Payeco.IF.collection_public_key);
                if (!b) {
                    retMsgJson = "{\"RetCode\":\"E101\",\"RetMsg\":\"验证签名失败!\"}";
                    System.out.println("sync verify sign error!");
                }else{
                    // 签名验证成功后，需要对订单进行后续处理
                    Order order = orderService.get(merchOrderId);
                    InvokeLog log = invokeLogService.getByOrderId(order.getId());
                    String returnUrl = log.getReturnUrl();
                    if ("0000".equals(respCode)) { // 订单已支付
                        // 1、检查Amount和商户系统的订单金额是否一致
                        // 2、订单支付成功的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理）；
                        // 3、返回响应内容

//                        if(order != null && order.getPaymentStatus().equals(Order.WAIT_PAYMENT)){
//                            order.setPaymentStatus(Order.HAS_PAID);
//                            order.setProcDate(DateUtils.getCurrentTime());
//                            orderService.save(order);
//                        }

                        retMsgJson = "{\"RetCode\":\"0000\",\"RetMsg\":\"订单已支付\"}";
                        System.out.println("sync orders has bean paid!");
                        returnUrl += "?code=0000&message="+ URLEncoder.encode("订单已支付","UTF-8");
                    } else {
                        // 1、订单支付失败的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理，避免成功后又修改为失败）；
                        // 2、返回响应内容
                        retMsgJson = "{\"RetCode\":\"E102\",\"RetMsg\":\"订单支付失败+"+status+"\"}";
                        System.out.println("sync orders of payment failure!status="+status);
                        returnUrl += "?code=E102&message="+ URLEncoder.encode("订单支付失败","UTF-8");
                    }
                    response.sendRedirect(returnUrl);

                }
            } catch (Exception e) {
                System.out.println("sync processing error!e=" + e.getMessage());
                String url = baseUrl + "?code=W101&message="+ URLEncoder.encode("支付服务异常","UTF-8");
                //String url = baseUrl + "?code=W101";
                response.sendRedirect(url);
            }
            System.out.println("-----同步通知完成----");
            //返回数据
        }
    }

    private String formatAmount(double amt) {
        DecimalFormat numFormat=new DecimalFormat ("0.00");
        return numFormat.format(amt);
    }
    public static void main(String[] args) {
	}
}
